<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统用户管理</span>
        </div>
      </template>
      <el-table v-loading="loading" :data="users" stripe style="width: 100%">
        <el-table-column label="ID" prop="userId" width="80" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="角色" prop="role" />
        <el-table-column label="订阅状态" prop="subscription" />
        <el-table-column label="账户状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'info'">
              {{ scope.row.isActive ? '已激活' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" title="编辑用户" width="500px">
      <el-form v-if="editForm" :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input :value="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="学生" value="STUDENT" />
            <el-option label="教师" value="TEACHER" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item label="订阅状态">
          <el-select v-model="editForm.subscription" placeholder="请选择订阅状态">
            <el-option label="免费" value="NORMAL" />
            <el-option label="会员" value="PREMIUM" />
          </el-select>
        </el-form-item>
        <el-form-item label="账户状态">
          <el-switch v-model="editForm.isActive" active-text="激活" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :loading="updateLoading" type="primary" @click="submitUpdate">
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { apiClient, handleErrorAndRedirect } from '@/api'
import { ElMessage } from 'element-plus'

const users = ref([])
const loading = ref(true)
const updateLoading = ref(false)

const dialogVisible = ref(false)
const editForm = reactive<any>({
  userId: null,
  username: '',
  role: '',
  subscription: '',
  isActive: false,
})

const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await apiClient.get('/admin/users')
    users.value = response.data.map((user: any) => ({
      ...user,
      isActive: user.active,
      subscription: user.subscription || 'NORMAL',
    }))
  } catch (error) {
    handleErrorAndRedirect(error, '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleEdit = (user: any) => {
  Object.assign(editForm, {
    userId: user.userId,
    username: user.username,
    role: user.role,
    subscription: user.subscription || 'NORMAL',
    isActive: user.isActive,
  })
  dialogVisible.value = true
}

const submitUpdate = async () => {
  updateLoading.value = true
  try {
    await apiClient.put(`/admin/users/${editForm.userId}`, {
      role: editForm.role,
      subscription: editForm.subscription,
      isActive: editForm.isActive,
    })
    ElMessage.success('用户信息更新成功！')
    dialogVisible.value = false
    await fetchUsers()
  } catch (error: any) {
    const message = error.response?.data?.message || '更新失败'
    ElMessage.error(message)
  } finally {
    updateLoading.value = false
  }
}

fetchUsers()
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  font-weight: 600;
  font-size: 18px;
}
</style>
